from flask import Flask, request, jsonify
from flask_cors import CORS
from BusinessAttributesFunc import BusinessAttributesAnalyzer
from BusinessNameFunc import BusinessApi
from DistanceFunc import DistanceApi
from Review_text import UserReviewApi
from UserFriends import UserFriendApi
from User_id import UserApi
import json

# 创建 Flask 应用
app = Flask(__name__)
CORS(app)

def fix_json_format(data):
    """
    修复 JSON 格式，将字符串类型的布尔值转换为布尔值，并解析嵌套的 JSON 字符串
    """
    def parse_json_string(obj):
        if isinstance(obj, dict):
            for key, value in obj.items():
                if isinstance(value, str) and value.startswith('{') and value.endswith('}'):
                    try:
                        obj[key] = parse_json_string(json.loads(value))
                    except json.JSONDecodeError:
                        pass
                elif value == "True":
                    obj[key] = True
                elif value == "False":
                    obj[key] = False
                elif value == "None":
                    obj[key] = None
        elif isinstance(obj, list):
            for i, item in enumerate(obj):
                if isinstance(item, str) and item.startswith('{') and item.endswith('}'):
                    try:
                        obj[i] = parse_json_string(json.loads(item))
                    except json.JSONDecodeError:
                        pass
                elif item == "True":
                    obj[i] = True
                elif item == "False":
                    obj[i] = False
                elif item == "None":
                    obj[i] = None
        return obj

    return parse_json_string(data)

@app.route('/get_businesses', methods=['GET'])
def get_businesses():
    # 创建 DistanceApi 实例
    distance_api = DistanceApi()
    try:
        # 从请求参数中获取经纬度和最大距离
        longitude = float(request.args.get('longitude'))
        latitude = float(request.args.get('latitude'))
        status = int(request.args.get('status'))
        # max_distance = float(request.args.get('max_distance'))

        # 调用 DistanceApi 的 run 方法
        result_df = distance_api.run(longitude, latitude, status)

        # 将 DataFrame 转换为 JSON 格式
        result_json = result_df.toJSON().collect()

        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]

        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })

@app.route('/get_business_stats', methods=['GET'])
def get_business_stats():
    # 创建 BusinessApi 实例
    business_api = BusinessApi()
    try:
        # 从请求参数中获取商户名称
        business_name = request.args.get('business_id')

        # 调用 BusinessApi 的 run 方法
        result_df = business_api.run(business_name)

        # 检查是否有结果
        if result_df is None:
            return jsonify({
                "status": "error",
                "message": "No business found with the provided name."
            })

        # 将 DataFrame 转换为 JSON 格式
        result_json = result_df.toJSON().collect()

        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]

        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })

@app.route('/get_business_attributes', methods=['GET'])
def get_business_attributes():
    # 创建 BusinessAttributesAnalyzer 实例
    attributes_analyzer = BusinessAttributesAnalyzer()
    try:
        # 调用 BusinessAttributesAnalyzer 的 run 方法
        result_df = attributes_analyzer.run()

        # 将 DataFrame 转换为 JSON 格式
        result_json = result_df.toJSON().collect()

        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]

        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })

@app.route('/get_user_info', methods=['GET'])
def get_user_info():
    # 创建 UserApi 实例
    user_api = UserApi()
    try:
        # 从请求参数中获取用户 ID
        user_id = request.args.get('user_id')

        # 调用 UserApi 的 run 方法
        result_df = user_api.run(user_id)

        # 检查是否有结果
        if result_df is None:
            return jsonify({
                "status": "error",
                "message": "No user found with the provided ID."
            })

        # 将 DataFrame 转换为 JSON 格式
        result_json = result_df.toJSON().collect()

        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]

        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })


@app.route('/get_review_info', methods=['GET'])
def get_review_info():
    # 创建 UserApi 实例
    user_api = UserReviewApi()
    try:
        # 从请求参数中获取用户 ID
        user_id = request.args.get('user_id')

        # 调用 UserApi 的 run 方法
        result_df = user_api.run(user_id)

        # 检查是否有结果
        if result_df is None:
            return jsonify({
                "status": "error",
                "message": "No user found with the provided ID."
            })

        # 将 DataFrame 转换为 JSON 格式
        result_json = result_df.toJSON().collect()

        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]

        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })

@app.route('/get_user_friends', methods=['GET'])
def get_user_friends():
    # 创建 UserApi 实例
    user_api = UserFriendApi()
    try:
        # 从请求参数中获取用户 ID
        user_id = request.args.get('user_id')
        # 调用 UserApi 的 run 方法
        result_df = user_api.run(user_id)
        # 检查是否有结果
        if result_df is None:
            return jsonify({
                "status": "error",
                "message": "No user found with the provided ID."
            })
        result_json = result_df.toJSON().collect()
        # 解析 JSON 字符串并修复格式
        fixed_result = [fix_json_format(json.loads(item)) for item in result_json]
        # 返回修复后的 JSON 格式的结果
        return jsonify(fixed_result)

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        })
if __name__ == '__main__':
    # 启动 Flask 应用
    app.run(host='0.0.0.0', port=5000, debug=True)